package com.power.sifa.correction.service.impl;

import cn.hutool.core.lang.id.NanoId;
import com.plf.core.common.service.BaseServiceImpl;
import com.power.sifa.correction.dao.Crw_rule_personDao;
import com.power.sifa.correction.model.Crw_rule_person;
import com.power.sifa.correction.model.pageInfo.Crw_rule_personPageInfo;
import com.power.sifa.correction.service.Crw_rule_personService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 *  预警规则的人员业务层实现
 */
@Service
public class Crw_rule_personServiceImpl extends BaseServiceImpl implements Crw_rule_personService {

    @Autowired
    private Crw_rule_personDao dao;

    @Resource
    private RuleRecordCacheService ruleRecordCacheService;

    @Override
    public Crw_rule_person getById(Serializable id) {
        return dao.findById(id).orElse(null);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdate(Crw_rule_person crw_rule_person) {
    	// save 如果数据库不存在这条数据，就会执行保存（即将这条数据插入到数据库）；如果数据库存在这条数据，就会根据主键去更新这条数据
        if (crw_rule_person.getPrimaryKey() != null) {
        	 Crw_rule_person crw_rule_personfDb = dao.findById(crw_rule_person.getPrimaryKey()).orElse(null);
             if(crw_rule_personfDb != null) {
                BeanUtils.copyProperties(crw_rule_person, crw_rule_personfDb);
                dao.save(crw_rule_personfDb);
                return;
             }
        }
        dao.save(crw_rule_person);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String id) {
        List<String> ids = new ArrayList<>();
        ids.add(id);
        List<Crw_rule_person> persons = dao.findByIds(ids);
        dao.deleteById(id);
    }

    @Override
    public Page<Crw_rule_person> findAll(Crw_rule_personPageInfo pageInfo) {
        //排序等定义
        Sort sort;
        if("asc".equals(pageInfo.getOrder())) {
            sort = Sort.by(Sort.Direction.ASC, pageInfo.getSort());
        }else {
            sort = Sort.by(Sort.Direction.DESC, pageInfo.getSort());
        }
        //分页的定义
        Pageable pageable = PageRequest.of(pageInfo.getPageNumber()<=1 ? 0 : pageInfo.getPageNumber()-1, pageInfo.getPageSize(), sort);
        //查询条件
        Specification spec = this.createSpecification(pageInfo);
        return dao.findAll(spec, pageable);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeByIds(List<String> ids) {
        List<Crw_rule_person>  persons = dao.findByIds(ids);
        dao.removeByIds(ids);
    }
    
    @Override
	public List<Crw_rule_person> findAll() {
		return dao.findAll();
	}
	
	@Override
	public void saveAll(List<Crw_rule_person> list) {
		dao.saveAll(list);
	}

    @Override
    public List<Crw_rule_person> getRuleByPersonIds(List<String> personIds) {
        return dao.getRuleByPersonIds(personIds);
    }

    @Override
    public List<Crw_rule_person> getRuleByPersonId(String personId) {
        return dao.getRuleByPersonId(personId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeByRuleId(String ruleId) {
        List<Crw_rule_person> persons = dao.findByRuleId(ruleId);
        dao.removeByRuleId(ruleId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeByRuleIds(List<String> list) {
        List<Crw_rule_person> persons = dao.findByRuleIds(list);
        dao.removeByRuleIds(list);
    }

    @Override
    public List<String> findPersonIdsByRuleId(String ruleId) {
        return dao.findPersonIdsByRuleId(ruleId);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveAll(String ruleId, List<String> personIds) {
        if (!CollectionUtils.isEmpty(personIds)) {
            List<Crw_rule_person> persons = personIds.stream().map(personId -> {
                Crw_rule_person person = new Crw_rule_person();
                person.setId(NanoId.randomNanoId());
                person.setPerid(personId);
                person.setRuleid(ruleId);
                return person;
            }).collect(Collectors.toList());
            this.saveAll(persons);
        }
    }

    /**
     * service 层进行新增，删除。修改后同步到redis数据 TOFIX: 暂时不使用该方法，避免redis和数据库查询不一致
     * @param personIds
     */
    private void setRedisCacheByPersons(List<String> personIds) {
        CompletableFuture.runAsync(() ->
                personIds.stream().forEach(el -> {
                    ruleRecordCacheService.initRuleCacheByPersonId(el);
                })
        );
    }

}
